import mysql from "mysql2/promise";

async function execute(sql: string) {
  let connection = await mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "123456",
  });

  let result = connection.execute(sql);

  connection.end();

  return result;
}

export class DatabaseFactory {
  public connection: any;

  async init() {
    this.connection = await mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "123456",
    });

    return this;
  }

  getDatabase(name: string): Database {
    return new Database(name, this.connection);
  }

  async getList() {
    let result = await execute("SHOW DATABASES");

    let newResult = (result[0] as []).map((item: any) => {
      return { name: item.Database };
    });

    return newResult;
  }
}

export class Database {
  constructor(public name: string, public connection: any) {}

  async create(): Promise<Database> {
    // 创建数据库
    await execute("CREATE DATABASE " + this.name + ";");

    return this;
  }

  getTable(name: string): Table {
    const table = new Table(name);
    table.database = this;
    return table;
  }

  async createTable(name: string, fields: Field[]): Promise<boolean> {
    let primaryKey = "";
    let fieldsString = fields.map((item: any) => {
      if (item.isPrimaryKey) {
        primaryKey = item.name;
      }
      return item.toString();
    });
    console.log(fieldsString);

    if (primaryKey) {
      fieldsString.push("PRIMARY KEY (`" + primaryKey + "`)");
    }

    await execute(
      "CREATE TABLE `" +
        this.name +
        "`.`" +
        name +
        "` (" +
        fieldsString.join(",") +
        ")"
    );

    return true;
  }

  async getTables() {
    let result = await execute(
      "SELECT table_name FROM information_schema.tables WHERE table_schema='" +
        this.name +
        "';"
    );

    return (result[0] as []).map((item: any) => {
      return {
        name: item.table_name,
      };
    });
  }

  async remove(): Promise<boolean> {
    // const connection = await getConnection();

    // await connection.execute("DROP DATABASE " + this.name + ";");

    // connection.end();

    return true;
  }
}

export class Field {
  static INT = "INT";
  static VARCHAR = "VARCHAR";
  static CHAR = "CHAR";

  dataType?: string;

  isUnsigned: boolean = false;

  private isPrimaryKey = false;

  private isNull = false;

  private isAutoIncrement = false;

  private comment = "";

  constructor(public name: string) {}

  toString() {
    let segments = [
      this.name,
      this.dataType,
      this.isUnsigned ? "UNSIGNED" : "",
      this.isNull ? "NULL" : "NOT NULL",
      this.isAutoIncrement ? "AUTO_INCREMENT" : "",
      this.comment.length > 0 ? "COMMENT '" + this.comment + "'" : "",
    ].filter((value) => value !== undefined && value.length > 0);
    return segments.join(" ").trimEnd();
  }

  setDataType(dataType: string, limit: string): Field {
    this.dataType = dataType + "(" + limit + ")";
    return this;
  }

  setComment(value: string) {
    this.comment = value;
    return this;
  }

  setUnsigned(value: boolean): Field {
    this.isUnsigned = value;
    return this;
  }

  setNull(value: boolean): Field {
    this.isNull = value;
    return this;
  }

  setAutoIncrement(value: boolean): Field {
    this.isAutoIncrement = value;
    return this;
  }

  setPrimaryKey(value: boolean): Field {
    this.isPrimaryKey = value;
    return this;
  }
}

export class Table {
  private fields: Array<any> = [];

  public database?: Database;

  constructor(public name: string) {}

  setFields(value: Array<any>): Table {
    this.fields = value;
    return this;
  }

  async remove(): Promise<boolean> {
    await execute(
      "DROP TABLE `" + this.database?.name + "`.`" + this.name + "`"
    );

    return true;
  }
}

// export class Database {
//   constructor(public name: string) {}

//   async create(): Promise<Database> {
//     const connection = await getConnection();

//     // 创建数据库
//     await connection.execute("CREATE DATABASE " + this.name + ";");

//     // 关闭数据库连接
//     connection.end();

//     return this;
//   }

//   getTable(name: string): Table {
//     const table = new Table(name);
//     table.database = this;
//     return table;
//   }

//   async remove(): Promise<boolean> {
//     const connection = await getConnection();

//     await connection.execute("DROP DATABASE " + this.name + ";");

//     connection.end();

//     return true;
//   }
// }

// /**
//  * 移除数据库
//  * @param string name
//  * @returns
//  */
// export async function remove(name: string): Promise<boolean> {
//   const mysql = await import("mysql2/promise");

//   const connection = await mysql.createConnection({
//     host: "localhost",
//     user: "root",
//     password: "123456",
//   });

//   // 创建数据库
//   await connection.execute("DROP DATABASE IF EXISTS " + name + ";");

//   // 关闭数据库连接
//   connection.end();

//   return true;
// }

// /**
//  * 修改数据库名称
//  * @param oldName
//  * @param newName
//  * @returns
//  */
// export async function update(
//   oldName: string,
//   newName: string
// ): Promise<boolean> {
//   const connection = await getConnection();

//   await connection.execute("DROP DATABASE " + oldName + ";");

//   await connection.execute("CREATE DATABASE " + newName + ";");

//   connection.end();

//   return true;
// }
